package com.fatan.xiaopacai.mvvm.view

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.fatan.xiaopacai.R
import com.fatan.xiaopacai.mvvm.model.PuKe
import com.fatan.xiaopacai.mvvm.model.allPuKe
import com.fatan.xiaopacai.mvvm.model.getRulerByPuke
import com.fatan.xiaopacai.mvvm.viewmodel.XiaoJiePukeViewModel
import com.fatan.xiaopacai.ui.theme.themeColor
import com.fatan.xiaopacai.util.ToastUtil

/**
 * @author: WangYeTong
 * @date: 2024/1/8 17:43
 * @remake: 小姐牌，以酒坑友扑克
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun XiaoJiePukeCompose(
    navHostController: NavHostController, xiaoJiePukeViewModel: XiaoJiePukeViewModel = viewModel()
) {
    val playerList by remember { xiaoJiePukeViewModel.playerList }
    val selectedPlayerIndex by remember { xiaoJiePukeViewModel.selectedPlayerIndex }
    val newPuke by remember { xiaoJiePukeViewModel.newPuke }
    val playedPukeList by remember { xiaoJiePukeViewModel.playedPuke }
    var isShowInputDialog by remember { mutableStateOf(false) }
    var isShowDeletePlayerDialog by remember { mutableStateOf(false) }
    var longPressPlayerIndex by remember { xiaoJiePukeViewModel.longPressPlayerIndex }
    if (isShowInputDialog) {
        var inputContent by remember { mutableStateOf("") }
        AlertDialog(onDismissRequest = { isShowInputDialog = false }, confirmButton = {
            Button(onClick = {
                if (inputContent.isEmpty()) {
                    ToastUtil.show("玩家名字不能为空")
                } else {
                    isShowInputDialog = false
                    xiaoJiePukeViewModel.addPlayer(inputContent)
                }
            }) {
                Text(text = "确定")
            }
        }, dismissButton = {
            Button(onClick = { isShowInputDialog = false }) {
                Text(text = "取消")
            }
        }, title = { Text(text = "添加玩家") }, text = {
            OutlinedTextField(value = inputContent, onValueChange = { inputContent = it }, label = { Text(text = "请输入玩家姓名") })
        })
    }
    if (isShowDeletePlayerDialog && playerList.size > longPressPlayerIndex) {
        AlertDialog(onDismissRequest = { isShowDeletePlayerDialog = false }, confirmButton = {
            Button(onClick = {
                isShowDeletePlayerDialog = false
                xiaoJiePukeViewModel.removePlayer(playerList[longPressPlayerIndex])
                //移除完成，更新当前选中角标
                if (selectedPlayerIndex >= longPressPlayerIndex) {
                    if (selectedPlayerIndex != 0) {
                        xiaoJiePukeViewModel.setSelectedPlayerIndex(selectedPlayerIndex - 1)
                    }
                }
            }) {
                Text(text = "删除")
            }
        }, dismissButton = {
            Button(onClick = { isShowDeletePlayerDialog = false }) {
                Text(text = "取消")
            }
        }, text = {
            Text(text = "是否删除玩家:${playerList[longPressPlayerIndex].name}")
        })
    }

    Column {
        TitleBar(titleText = "小姐牌", backClick = { navHostController.navigateUp() }, rightText = "游戏规则", rightClick = {
            navHostController.navigate(Nav.XiaoJiePukeRuler.route)
        })

        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp)
        ) {
            Column {
                Spacer(modifier = Modifier.height(100.dp))
                LazyColumn(
                    modifier = Modifier
                        .border(1.dp, Color.White)
                        .width(100.dp)
                ) {
                    item {
                        PlayerItem(name = "玩家")
                        Divider(color = Color.White, thickness = 1.dp)
                    }

                    itemsIndexed(playerList) { index, item ->
                        PlayerItem(name = item.name, selectedPlayerIndex == index, modifier = Modifier.combinedClickable(onLongClick = {
                            longPressPlayerIndex = index
                            isShowDeletePlayerDialog = true
                        }) {
                            xiaoJiePukeViewModel.setSelectedPlayerIndex(index)
                        })
                        Divider(color = Color.White, thickness = 1.dp)
                    }

                    //+号，添加玩家
                    item {
                        Box(
                            modifier = Modifier
                                .height(50.dp)
                                .fillMaxWidth()
                                .clickable {
                                    isShowInputDialog = true
                                }, contentAlignment = Alignment.Center
                        ) {
                            Text(text = "+", fontSize = 25.sp, fontWeight = FontWeight.Bold, color = Color.White)
                        }
                    }
                }
            }

            Row(
                modifier = Modifier
                    .padding(start = 112.dp, end = 12.dp, top = 12.dp)
                    .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically
            ) {
                Button(onClick = { xiaoJiePukeViewModel.reset() }, modifier = Modifier.weight(1f)) {
                    Text(text = "洗牌")
                }
                Spacer(modifier = Modifier.width(12.dp))
                Text(
                    text = "剩余牌数:${allPuKe.size - playedPukeList.size}/${allPuKe.size}", color = Color.White, fontSize = 18.sp
                )
            }
            XiaoJiePuke(puKe = newPuke, modifier = Modifier
                .padding(start = 132.dp, top = 100.dp, end = 32.dp, bottom = 250.dp)
                .clickable {
                    if (playerList.isNotEmpty()) {
                        xiaoJiePukeViewModel.randomNewPuke()
                    }
                })
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
                Box(
                    modifier = Modifier
                        .height(250.dp)
                        .padding(start = 132.dp, top = 12.dp)
                ) {
                    Divider(thickness = 1.dp, color = Color.White)
                    LazyVerticalGrid(columns = GridCells.Fixed(3)) {
                        if (playerList.isNotEmpty()) {
                            itemsIndexed(playerList[selectedPlayerIndex].pukeList.reversed()) { index, item ->
                                Box(
                                    modifier = Modifier
                                        .height(60.dp)
                                        .border(1.dp, Color.White), contentAlignment = Alignment.Center
                                ) {
                                    Text(text = item.name, color = Color.White, fontSize = 18.sp)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/**
 * 玩家列表
 */
@Composable
fun PlayerItem(name: String, selected: Boolean = false, modifier: Modifier = Modifier) {
    val backgroundColor = if (selected) {
        themeColor
    } else {
        Color.Transparent
    }
    Box(
        modifier = modifier
            .height(50.dp)
            .background(backgroundColor)
            .fillMaxWidth(), contentAlignment = Alignment.Center
    ) {
        Text(
            text = name,
            fontSize = 18.sp,
            color = Color.White,
        )
    }
}

@Composable
fun XiaoJiePuke(puKe: PuKe, modifier: Modifier = Modifier) {
    val ruler = getRulerByPuke(puKe)
    Box(
        modifier = modifier
            .border(1.dp, Color.White, MaterialTheme.shapes.medium)
            .fillMaxSize()
    ) {
        Column(
            modifier = Modifier
                .padding(12.dp)
                .fillMaxSize()
        ) {

            Text(
                text = puKe.name, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = Color.White
            )

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 12.dp), contentAlignment = Alignment.Center
            ) {
                Text(
                    text = ruler.first, color = Color.White, fontSize = 28.sp, fontWeight = FontWeight.Bold
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 12.dp), contentAlignment = Alignment.Center
            ) {
                Text(
                    text = ruler.second, color = Color.White, fontSize = 18.sp, textAlign = TextAlign.Center
                )
            }


        }
    }
}

